TOOL.Category = "Space Weapons"
TOOL.Name = "Coil Gun"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.ent = {} 
TOOL.ClientConVar["Power"] = "10"
cleanup.Register( "coilgun" )

if CLIENT then
   language.Add ("Tool_coilgun_name", "Coil Gun")
   language.Add ("Tool_coilgun_desc", "A customizable cannon.")
   language.Add ("Tool_coilgun_0", "Primary: Spawn a Coil Gun")
   language.Add ("Undone_coilgun", "Coil Gun undone.")
end



function TOOL:LeftClick( trace )
	if (CLIENT) then return true end
	local ply = self:GetOwner()

	if ( !trace.Hit ) then return end

	if ( SERVER and !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	   local Power = self:GetClientNumber("power")

	local Weapon = MakeCoil(Power, trace)
	
	local phys = Weapon:GetPhysicsObject()  	
	if (phys:IsValid()) then  		
		local weld = constraint.Weld(Weapon, trace.Entity, 0, trace.PhysicsBone, 0)
		local nocollide = constraint.NoCollide(Weapon, trace.Entity, 0, trace.PhysicsBone)
	end 
	
	undo.Create("coilgun")
		undo.AddEntity( Weapon )
		undo.AddEntity( weld )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()
	
   return true
end

function TOOL:RightClick( trace )
	if (CLIENT) then return true end
	local ply = self:GetOwner()

	if ( !trace.Hit ) then return end

	if ( SERVER and !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	   local Power = self:GetClientNumber("power")

	local Weapon = MakeCoil(Power, trace)
	
	
	undo.Create("coilgun")
		undo.AddEntity( Weapon )
		undo.SetPlayer( ply )
	undo.Finish()
	
   return true
end



if (SERVER) then

	 function MakeCoil(Pow, trace)
		
		local Ang = (trace.HitNormal:Angle() + Angle(90,0,0))
		local Pos = trace.HitPos + trace.HitNormal* 8
	
	local gun = ents.Create("CG")
    gun:SetPos(Pos)
	gun:SetAngles( Ang)
	gun:Spawn()
    gun:Activate()
    gun:Setup(Pow)
	
	return gun
	end

end

if CLIENT then
function TOOL.BuildCPanel(panel)
   
   panel:AddControl("Header", {Text = "#Tool_coilgun_name", Description = "#Tool_laser_desc"})

   panel:AddControl("Slider", {
      Label = "Power",
      Type = "Integer",
      Min = "10",
      Max = "50",
      Command = "coilgun_Power"})

end 
end 